package com.android.accessibility.service;

import android.accessibilityservice.AccessibilityService;
import android.content.Intent;
import android.view.accessibility.AccessibilityEvent;

import com.android.accessibility.function.Accessibility;
import com.android.accessibility.function.AudoSendMsgAccessibility;
import com.android.accessibility.function.AutoClicklikeAccessibility;
import com.android.accessibility.function.WechatGrabAccessibility;
import com.android.accessibility.utils.Constant;
import com.android.accessibility.utils.Log;
import com.android.accessibility.utils.Utils;

public class MyAccessibilityService extends AccessibilityService {

    public static CharSequence sLastClassName = null;
    private Accessibility mAccessibility;
    private boolean mStop = true;

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (mAccessibility == null) {
            mAccessibility = getAccessibility();
        }
        if (mAccessibility != null) {
            int eventType = event.getEventType();
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                mAccessibility.setClassName(event.getClassName());
                sLastClassName = event.getClassName();
            }
            if (!mStop) {
                mAccessibility.onAccessibilityEvent(event);
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            Log.d(Log.TAG, "Action : " + intent.getAction());
            if (Constant.ACTION_START.equals(intent.getAction())) {
                if (mAccessibility == null) {
                    mAccessibility = getAccessibility();
                }
                if (mAccessibility != null) {
                    mStop = false;
                    mAccessibility.start();
                }
            } else if (Constant.ACTION_STOP.equals(intent.getAction())) {
                if (mAccessibility != null) {
                    mStop = true;
                    mAccessibility.stop();
                    mAccessibility = null;
                }
            } else if (Constant.ACTION_RESET.equals(intent.getAction())) {
                mAccessibility = null;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onInterrupt() {
    }

    private Accessibility getAccessibility() {
        int access = Utils.getAccessibility(this);
        if (access == Constant.ACCESSIBILITY_CLICKLIKE) {
            return new AutoClicklikeAccessibility(this);
        } else if (access == Constant.ACCESSIBILITY_SENDMSG) {
            return new AudoSendMsgAccessibility(this);
        } else if (access == Constant.ACCESSIBILITY_WXGRAB) {
            return new WechatGrabAccessibility(this);
        }
        return null;
    }
}
